package com.duanjw.springframework.ioc.factory;

import com.duanjw.springframework.ioc.factory.dao.UserDao;
import com.duanjw.springframework.ioc.factory.dao.impl.UserDaoImplFactoryBean;
import org.springframework.context.support.GenericApplicationContext;

/**
 * FactoryBean应用
 * 演示FactoryBean的使用
 *
 * @author duanjw
 */
public class FactoryBeanApplication {
    public static void main(String[] args) {
        // 1. 使用GenericApplicationContext构建一个ApplicationContext
        GenericApplicationContext ctx = new GenericApplicationContext();

        // 2. 注册`UserDaoImplFactoryBean`，并设置beanName。
        // UserDaoImplFactoryBean是一个实现了FactoryBean的bean
        ctx.registerBean("userDaoImplFactoryBean", UserDaoImplFactoryBean.class);

        // 3. 初始化容器
        ctx.refresh();

        // 4. 获取`UserDaoImplFactoryBean`
        // UserDaoImplFactoryBean是一个FactoryBean，所以beanName会在原先beanName之前加一个"&"（无论是注册FactoryBean时设置了beanName，还是Spring自动帮我们生成的beanName，都会在之前加一个`&`）
        UserDaoImplFactoryBean userDaoImplFactoryBean = (UserDaoImplFactoryBean) ctx.getBean("&userDaoImplFactoryBean");

        // 5. 获取`UserDaoImplFactoryBean`给我们生成的bean
        // beanName就是FactoryBean的beanName
        UserDao userDao = ctx.getBean("userDaoImplFactoryBean", UserDao.class);

        System.out.println("UserDaoImplFactoryBean：" + userDaoImplFactoryBean);
        System.out.println("userDao：" + userDao);

    }
}
